package org.chispa.api.visitors;

import java.io.File;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.spec.IvParameterSpec;

import org.chispa.api.hashers.IndexingHash;
import org.chispa.api.hashers.StringHash;

import com.google.common.annotations.VisibleForTesting;

@VisibleForTesting
public class SimpleStringPVFactory extends AbstractSimpleVisitorFactory<String,String,String> {
	
	protected static final int MOD=32;
	protected static final int RAND_BITS=64;
	protected static File HMAC_KEY=new File("hmac.spec");
	
	private IndexingHash<String, String> hasher;
	
	public SimpleStringPVFactory(){};
	
	public SimpleStringPVFactory(IndexingHash<String, String> hasher){this.hasher=hasher;};

	@Override
	protected SingleParamVisitor<String, String> doCreateVisitor() throws NoSuchAlgorithmException {
		if(!HMAC_KEY.exists())
		{
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			String passw=new BigInteger(RAND_BITS, random).toString(MOD);
			writeOut(HMAC_KEY,passw);
		}
		String hmac_key=readIn(HMAC_KEY,String.class);
		if(hasher==null)
			hasher=new StringHash(MOD,hmac_key);
		return new StringParamVisitor(cipher, spec, new IvParameterSpec(ivpar.toByteArray()),hasher);
	}

	@Override
	public SingleParamVisitor<String, String> createVisitorForExpr()
			throws NoSuchAlgorithmException {
		return createVisitor();
	}

}
